package com.itheima.security;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserService implements UserDetailsService {
    //模拟数据库中的用户数据
    public  static Map<String, com.itheima.pojo.User> map = new HashMap<>();
    static {
        com.itheima.pojo.User user1 = new com.itheima.pojo.User();
        user1.setUsername("admin");
        user1.setPassword("{noop}admin");//相当于数据库中保存的密码

        com.itheima.pojo.User user2 = new com.itheima.pojo.User();
        user2.setUsername("xiaoming");
        user2.setPassword("{noop}1234");

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(username == null || username.equals("")){
            return null;
        }
        com.itheima.pojo.User user = map.get(username);//相当于查询数据库
        String passwordInDb = user.getPassword();
        if(user == null){
            return null;
        }
        List<GrantedAuthority> list = new ArrayList<>();
        //后期需要根据数据库中查询出的权限和角色动态授权
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        User user1 = new User(username,passwordInDb,list);
        return user1;
    }
}
